import { createSlice } from '@reduxjs/toolkit'
import { clearToken, getToken, setToken } from '@/utils/token'
import { getUserRegisterAPI, getUserLoginAPI, getUserInfoAPI } from '@/api/user'
import { message } from 'antd'
import { clearUserInfoKey, getUserInfoKey, setUserInfoKey } from '@/utils/userInfo'
const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
    userId: 0,
    userInfo: JSON.parse(getUserInfoKey()) || {}
  },
  // 同步修改方法
  reducers: {
    setUserToken (state, action) {
      state.token = action.payload
      setToken(state.token)
    },
    setUserId (state, action) {
      state.userId = action.payload
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
      setUserInfoKey(state.userInfo)
    },
    // 登出
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      clearToken()
      clearUserInfoKey()
    }
  }
})

// 解构出actionCreater
const { setUserToken, setUserId, setUserInfo, clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步封装
const fetchUserRegister = (formValue) => {
  return async () => {
      const res = await getUserRegisterAPI(formValue)
      if (res.code === 1) {
        message.success('注册成功')
        return true
      } else {
        message.error(res.msg)
        return false
      }
  }
}

// 异步封装,获取token
const fetchUserLogin = (formValue) => {
  return async (dispatch) => {
      const res = await getUserLoginAPI(formValue)
      if (res.code === 1) {
        dispatch(setUserToken(res.data.jwt))
        dispatch(setUserId(res.data.id))
        const res2 = await getUserInfoAPI(res.data.id)
        dispatch(setUserInfo(res2.data))
        message.success('登录成功')
        return true
      } else {
        message.error(res.msg)
        return false
      }
  }
}

const fetchUserInfo = (id) => {
  return async (dispatch) => {
    const res = await getUserInfoAPI(id)
    dispatch(setUserInfo(res.data))
    
  }
}

export { fetchUserRegister, fetchUserLogin, fetchUserInfo, clearUserInfo }

export default userReducer